package com.onLineCar.netty.serve;


import com.alibaba.fastjson.JSONObject;
import com.onLineCar.common.redis.service.RedisService;
import com.onLineCar.common.system.domain.SysUser;
import com.onLineCar.netty.protocol.command.MessageRequestPacket;
import com.onLineCar.netty.protocol.command.RegisterRequestPacket;
import com.onLineCar.netty.utils.SessionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 注册 绑定用户channel
 * @author holiday
 * date 2020-11-04
 */
@Component
@Sharable
public class RegisterRequestHandler extends SimpleChannelInboundHandler<RegisterRequestPacket>{

	@Autowired
	private RedisService redisService;

	private RegisterRequestHandler() {

	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RegisterRequestPacket registerRequestPacket) throws Exception {
		SysUser user = registerRequestPacket.getUser();
		SessionUtils.bindChannel(user, ctx.channel());

		List<Object> byRedisMessage = findByRedisMessage(String.valueOf(user.getUserId()));
		if (!CollectionUtils.isEmpty(byRedisMessage)){
			for (Object o : byRedisMessage) {
				MessageRequestPacket messageRequestPacket = JSONObject.parseObject(o.toString(), MessageRequestPacket.class);
				ByteBuf buffer = getByteBuf(ctx,messageRequestPacket.getMessage(),SessionUtils.getUser(SessionUtils.getChannel(messageRequestPacket.getToUserId())),messageRequestPacket.getFileType());
				ctx.channel().writeAndFlush(new TextWebSocketFrame(buffer));
			}
		}
		if (SessionUtils.hasLogin(ctx.channel())) {
			System.out.println("该用户已登录");
		}


	}

	public ByteBuf getByteBuf(ChannelHandlerContext ctx, String message, SysUser toUser, String fileType) {
		ByteBuf byteBuf = ctx.alloc().buffer();
		SysUser fromUser = SessionUtils.getUser(ctx.channel());
		JSONObject data = new JSONObject();
		data.put("type", 2);
		data.put("status", 200);
		JSONObject params = new JSONObject();
		params.put("message", message);
		params.put("fileType", fileType);
		params.put("fromUser", fromUser);
		params.put("toUser", toUser);
		data.put("params", params);
		byte []bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
		byteBuf.writeBytes(bytes);
		return byteBuf;
	}

	public List<Object> findByRedisMessage(String userId){
		return redisService.redisTemplate.opsForList().range("离线消息" + userId, 0, -1);
	}

}
